#!/usr/bin/env python3

# Standard lib imports
import argparse
import logging
import sys
import os
import json


# Local project imports
import src.exporter as exporter
import src.blockparse as blockparse

def main(args):
    # Parse bytecode
    logging.info("Reading from '%s'.", args.infile.name)
    if args.generate_interface:
        logging.info("Generating decompiler input interface")
        exporter.generate_interface()
        return
    if args.disassembly:
        blocks = blockparse.EVMDasmParser(args.infile).parse()
        metadata = {}
    else:
        bytecode = args.infile.read().strip()
        if os.path.exists(metad:= f"{args.infile.name[:-4]}_metadata.json"):
            metadata = json.load(open(metad))
        else:
            metadata = {}
        blocks = blockparse.EVMBytecodeParser(bytecode).parse()
    logging.info("Initial parsing completed.")

    logging.info("Writing facts to disk.")
    exporter.EVMBlockExporter(args.outdir, blocks, bytecode_hex=bytecode, metadata=metadata).export()

if __name__ == '__main__':
    # Configure argparse
    parser = argparse.ArgumentParser(
        description="Fact generation for EVM bytecode disassembly.")

    parser.add_argument("-a",
                    "--disassembly",
                    action="store_true",
                    default=False,
                    help="decompile dissassembled input.")

    parser.add_argument("--generate_interface",
                    action="store_true",
                    default=False,
                    help="generate .dl decompiler input interface.")
    

    parser.add_argument("infile",
                    nargs="?",
                    type=argparse.FileType("r"),
                    default=sys.stdin,
                    help="file from which decompiler input should be read "
                         "(stdin by default).")

    parser.add_argument("outdir",
                    nargs="?",
                    const="",
                    metavar="DIR",
                    default="",
                    help="produce facts for original bytecode input.")

    # Parse the arguments.
    args = parser.parse_args()
    main(args)


